package com.ctec.util;


import lombok.extern.slf4j.Slf4j;
import ru.yandex.clickhouse.ClickHouseConnection;
import ru.yandex.clickhouse.ClickHouseDataSource;
import ru.yandex.clickhouse.settings.ClickHouseProperties;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;


@Slf4j
public class createTable {
    private static String username = "";
    private static String password = "";
    private static String address = "jdbc:clickhouse://localhost:8123";
    private static String db = "default";
    private static int socketTimeout = 600000;


    public static void main(String[] args) throws SQLException {

        testCreateTable();

    }

    public static void testCreateTable() throws SQLException {
        log.info("创建 Clickhouse 表");
        String tableSql = "create table password_bank22(\n" +
                " id UInt32,\n" +
                " password String,\n" +
                " username String,\n" +
                " hash String,\n" +
                " salt String,\n" +
                " encryption_type String,\n" +
                " resource_path String,\n" +
                " create_time Datetime\n" +
                ") engine =MergeTree\n" +
                " partition by toYYYYMMDD(create_time)\n" +
                " primary key (id)\n" +
                " order by id;";
        Connection connection = getConn();
        Statement statement = connection.createStatement();
        boolean execute = statement.execute(tableSql);
        if(execute){
            System.out.println(execute);
            System.out.println("创建表成功");
        }else {
            System.out.println("创建失败");
        }

    }


    public static Connection getConn() {
        ClickHouseProperties properties = new ClickHouseProperties();
        properties.setUser(username);
        properties.setPassword(password);
        properties.setDatabase(db);
        properties.setSocketTimeout(socketTimeout);
        ClickHouseDataSource clickHouseDataSource = new ClickHouseDataSource(address, properties);
        ClickHouseConnection conn = null;
        try {
            conn = clickHouseDataSource.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
